//
// DotNetNuke - http://www.dotnetnuke.com
// Copyright (c) 2002-2010
// by Perpetual Motion Interactive Systems Inc. ( http://www.perpetualmotion.ca )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System;
using System.IO;
using System.Web.UI.WebControls;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Definitions;
using DotNetNuke.Security;
using DotNetNuke.UI.Utilities;
namespace DotNetNuke.Modules.Admin.ModuleDefinitions
{
	partial class EditModuleControl : DotNetNuke.Entities.Modules.PortalModuleBase
	{
		private DesktopModuleInfo _DesktopModule = null;
		private int ModuleDefId;
		private int ModuleControlId;
		protected DesktopModuleInfo DesktopModule {
			get {
				if (_DesktopModule == null) {
					_DesktopModule = DesktopModuleController.GetDesktopModuleByPackageID(PackageID);
				}
				return _DesktopModule;
			}
		}
		public int PackageID {
			get {
				int _PackageID = Null.NullInteger;
				if ((Request.QueryString["PackageID"] != null)) {
					_PackageID = Int32.Parse(Request.QueryString["PackageID"]);
				}
				return _PackageID;
			}
		}
		protected string ReturnURL {
			get { return EditUrl("PackageID", PackageID.ToString(), "Edit", "ModuleDefinitionID=" + ModuleDefId.ToString()); }
		}
		private void BindControlList(string strRoot, bool blnRecurse)
		{
			string[] arrFolders;
			string[] arrFiles;
			if (Directory.Exists(Request.MapPath(Common.Globals.ApplicationPath + "/" + strRoot))) {
				arrFolders = Directory.GetDirectories(Request.MapPath(Common.Globals.ApplicationPath + "/" + strRoot));
				if (blnRecurse) {
					foreach (string strFolder in arrFolders) {
						BindControlList(strFolder.Substring(Request.MapPath(Common.Globals.ApplicationPath).Length + 1).Replace('\\', '/'), blnRecurse);
					}
				}
				arrFiles = Directory.GetFiles(Request.MapPath(Common.Globals.ApplicationPath + "/" + strRoot), "*.ascx");
				foreach (string strFile in arrFiles) {
					string file = strRoot.Replace('\\', '/') + "/" + Path.GetFileName(strFile);
					cboSource.Items.Add(new ListItem(file, file.ToLower()));
				}
			}
		}
		private void LoadIcons()
		{
			string strRoot;
			string[] arrFiles;
			string strExtension;
			cboIcon.Items.Clear();
			cboIcon.Items.Add("<" + Services.Localization.Localization.GetString("Not_Specified") + ">");
			if (!String.IsNullOrEmpty(cboSource.SelectedItem.Value)) {
				strRoot = cboSource.SelectedItem.Value;
				strRoot = Request.MapPath(Common.Globals.ApplicationPath + "/" + strRoot.Substring(0, strRoot.LastIndexOf("/")));
				if (Directory.Exists(strRoot)) {
					arrFiles = Directory.GetFiles(strRoot);
					foreach (string strFile in arrFiles) {
						strExtension = Path.GetExtension(strFile).Replace(".", "");
						if ((Common.Globals.glbImageFileTypes + ",").IndexOf(strExtension + ",") != -1) {
							cboIcon.Items.Add(new ListItem(Path.GetFileName(strFile), Path.GetFileName(strFile).ToLower()));
						}
					}
				}
			}
		}
		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

			cboSource.SelectedIndexChanged += new EventHandler(cboSource_SelectedIndexChanged);
			cmdCancel.Click += new EventHandler(cmdCancel_Click);
			cmdDelete.Click += new EventHandler(cmdDelete_Click);
			cmdUpdate.Click += new EventHandler(cmdUpdate_Click);

			try {
				if ((Request.QueryString["moduledefid"] != null)) {
					ModuleDefId = Int32.Parse(Request.QueryString["moduledefid"]);
				} else {
					ModuleDefId = Null.NullInteger;
				}
				if ((Request.QueryString["modulecontrolid"] != null)) {
					ModuleControlId = Int32.Parse(Request.QueryString["modulecontrolid"]);
				} else {
					ModuleControlId = Null.NullInteger;
				}
				if (Page.IsPostBack == false) {
					lblModule.Text = DesktopModule.FriendlyName;
					ModuleDefinitionInfo objModuleDefinition = ModuleDefinitionController.GetModuleDefinitionByID(ModuleDefId);
					if (objModuleDefinition != null) {
						lblDefinition.Text = objModuleDefinition.FriendlyName;
					}
					ClientAPI.AddButtonConfirm(cmdDelete, Services.Localization.Localization.GetString("DeleteItem"));
					ModuleControlInfo objModuleControl;
					objModuleControl = ModuleControlController.GetModuleControl(ModuleControlId);
					BindControlList("DesktopModules", true);
					BindControlList("Admin/Skins", false);
					cboSource.Items.Insert(0, new ListItem("<" + Services.Localization.Localization.GetString("None_Specified") + ">", ""));
					if (!Null.IsNull(ModuleControlId)) {
						if (objModuleControl != null) {
							txtKey.Text = objModuleControl.ControlKey;
							txtTitle.Text = objModuleControl.ControlTitle;
							if (cboSource.Items.FindByValue(objModuleControl.ControlSrc.ToString().ToLower()) != null) {
								cboSource.Items.FindByValue(objModuleControl.ControlSrc.ToString().ToLower()).Selected = true;
								LoadIcons();
							} else {
								txtSource.Text = objModuleControl.ControlSrc;
							}
							if (cboType.Items.FindByValue(Convert.ToInt32(objModuleControl.ControlType).ToString()) != null) {
								cboType.Items.FindByValue(Convert.ToInt32(objModuleControl.ControlType).ToString()).Selected = true;
							}
							if (!Null.IsNull(objModuleControl.ViewOrder)) {
								txtViewOrder.Text = objModuleControl.ViewOrder.ToString();
							}
							if (cboIcon.Items.FindByValue(objModuleControl.IconFile.ToLower()) != null) {
								cboIcon.Items.FindByValue(objModuleControl.IconFile.ToLower()).Selected = true;
							}
							if (!Null.IsNull(objModuleControl.HelpURL)) {
								txtHelpURL.Text = objModuleControl.HelpURL;
							}
							if (objModuleControl.SupportsPartialRendering) {
								chkSupportsPartialRendering.Checked = true;
							}
						}
					} else {
						if (cboType.Enabled) {
							cboType.Items.FindByValue("0").Selected = true;
						} else {
							cboType.Items.FindByValue("-2").Selected = true;
						}
					}
				}
			} catch (Exception exc) {
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
		private void cboSource_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			LoadIcons();
		}
		private void cmdCancel_Click(object sender, EventArgs e)
		{
			try {
				Response.Redirect(ReturnURL, true);
			} catch (Exception exc) {
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
		private void cmdDelete_Click(object sender, EventArgs e)
		{
			try {
				if (!Null.IsNull(ModuleControlId)) {
					ModuleControlController.DeleteModuleControl(ModuleControlId);
				}
				Response.Redirect(ReturnURL, true);
			} catch (Exception exc) {
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
		private void cmdUpdate_Click(object sender, EventArgs e)
		{
			try {
				if (Page.IsValid == true) {
					if (cboSource.SelectedIndex != 0 || !String.IsNullOrEmpty(txtSource.Text))
					{
						ModuleControlInfo objModuleControl = new ModuleControlInfo();
						objModuleControl.ModuleControlID = ModuleControlId;
						objModuleControl.ModuleDefID = ModuleDefId;
						if (!String.IsNullOrEmpty(txtKey.Text)) {
							objModuleControl.ControlKey = txtKey.Text;
						} else {
							objModuleControl.ControlKey = Null.NullString;
						}
						if (!String.IsNullOrEmpty(txtTitle.Text)) {
							objModuleControl.ControlTitle = txtTitle.Text;
						} else {
							objModuleControl.ControlTitle = Null.NullString;
						}
						if (!String.IsNullOrEmpty(txtSource.Text)) {
							objModuleControl.ControlSrc = txtSource.Text;
						} else {
							objModuleControl.ControlSrc = cboSource.SelectedItem.Text;
						}
						objModuleControl.ControlType = (SecurityAccessLevel)Enum.Parse(typeof(SecurityAccessLevel), cboType.SelectedItem.Value);
						if (!String.IsNullOrEmpty(txtViewOrder.Text)) {
							objModuleControl.ViewOrder = int.Parse(txtViewOrder.Text);
						} else {
							objModuleControl.ViewOrder = Null.NullInteger;
						}
						if (cboIcon.SelectedIndex > 0) {
							objModuleControl.IconFile = cboIcon.SelectedItem.Text;
						} else {
							objModuleControl.IconFile = Null.NullString;
						}
						if (!String.IsNullOrEmpty(txtHelpURL.Text)) {
							objModuleControl.HelpURL = txtHelpURL.Text;
						} else {
							objModuleControl.HelpURL = Null.NullString;
						}
						objModuleControl.SupportsPartialRendering = chkSupportsPartialRendering.Checked;
						try {
							ModuleControlController.SaveModuleControl(objModuleControl, true);
						} catch {
							DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, Services.Localization.Localization.GetString("AddControl.ErrorMessage", this.LocalResourceFile), DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
							return;
						}
						Response.Redirect(ReturnURL, true);
					} else {
						DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, Services.Localization.Localization.GetString("MissingSource.ErrorMessage", this.LocalResourceFile), DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
					}
				}
			} catch (Exception exc) {
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
	}
}
